package com.zhang.gateway.filter;

import com.zhang.gateway.pojo.bo.RequestBO;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.time.LocalDateTime;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;

@Component
public class IpFilter implements GlobalFilter, Ordered {

    private static ConcurrentHashMap<String, RequestBO> ipRequestMap=new ConcurrentHashMap<>();

    @Value("${code.prevent.time}")
    private Integer time;
    @Value("${code.prevent.total}")
    private Integer total;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();

        String path=request.getPath().toString();
        if(path.startsWith("/api/user/register")){
            // 从request对象中获取客户端ip
            String clientIp = Objects.requireNonNull(request.getRemoteAddress()).getHostString();

            //判断方法是否存在于map中
            if(!ipRequestMap.containsKey(clientIp)){
                RequestBO requestBO = new RequestBO();
                requestBO.setIp(clientIp);
                requestBO.setBegin(LocalDateTime.now());
                requestBO.setEnd(LocalDateTime.now().plusSeconds(time));
                requestBO.setCount(1);
                ipRequestMap.put(clientIp,requestBO);
            }else{
                //判断ipRequestMap中得请求次数是否超了
                LocalDateTime now = LocalDateTime.now();
                RequestBO requestBO = ipRequestMap.get(clientIp);
                //时间已过，重新计时
                if (now.isAfter(requestBO.getEnd())){
                    requestBO.setBegin(now);
                    requestBO.setEnd(now.plusSeconds(time));
                    requestBO.setCount(0);
                    ipRequestMap.put(clientIp,requestBO);
                }
                Integer count = requestBO.getCount();
                //判断请求次数是否超过阈值
                if(count>total){
                    // 拒绝访问，返回
                    response.setStatusCode(HttpStatus.FORBIDDEN); // 状态码
                    String data = "code:403,message:fluently register and request forbidden";
                    DataBuffer wrap = response.bufferFactory().wrap(data.getBytes());
                    return response.writeWith(Mono.just(wrap));
                }else{
                    count++;
                    requestBO.setCount(count);
                    ipRequestMap.put(clientIp,requestBO);
                }
            }
        }
        // 合法请求，放⾏，执⾏后续的过滤器
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 1;
    }
}
